<template>
    <div class="reset-password-container">
        <h2>修改密码</h2>
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="reset-password-form">
            <el-form-item label="旧密码" prop="old_pwd">
                <el-input v-model="form.old_pwd" type="password" placeholder="请输入旧密码"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="new_pwd">
                <el-input v-model="form.new_pwd" type="password" placeholder="请输入新密码"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="re_pwd">
                <el-input v-model="form.re_pwd" type="password" placeholder="请确认新密码"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const formRef = ref(null)
const form = ref({
    old_pwd: '',
    new_pwd: '',
    re_pwd: ''
})

// 校验密码是否一致
const checkConfirmPassword = (rule, value, callback) => {
    if (value !== form.value.new_pwd) {
        callback(new Error("两次密码不一致"));
    } else {
        callback();
    }
}

const rules = {
    old_pwd: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    new_pwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    ],
    re_pwd: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { validator: checkConfirmPassword, trigger: "blur" }
    ]
}


import { useUserInfoStore } from '@/stores/user.js'
const userInfoStore = useUserInfoStore()

import { useTokenStore } from '@/stores/token.js'
const tokenStore = useTokenStore()
import { useRouter } from 'vue-router'
const router = useRouter()

import { getUserInfoResetPasswordService } from '@/api/user.js'
// 提交表单
const submitForm = async () => {
    console.log('form: ' + form);
    const result = await getUserInfoResetPasswordService(form.value)
    console.log('result: ' + result);
    ElMessage.success(result.message ? result.message : '修改成功')
    // 删除pinia中的数据
    userInfoStore.removeInfo()
    // 清除token
    tokenStore.removeToken()
    // 跳转到登录页
    router.push('/login')
}

// 重置表单
const resetForm = () => {
    formRef.value.resetFields()
}
</script>

<style scoped>
.reset-password-container {
    width: auto;
    margin: 0 auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
    background-color: #fff;
}

.reset-password-form {
    margin-top: 20px;
}
</style>